from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, GenericAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from users.serializers import CreateUserSerializer
from users.models import User
from users.serializers import UserDetailSerializer, EmailSerializer


# Create your views here.


# url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """
    邮箱验证
    """

    def get(self, request):
        # 1. 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})
            # 3. 返回响应


# 　url(r'^email/$', views.EmailView,as_view())
class EmailView(UpdateAPIView):
    """设置用户邮箱并发送验证"""
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    # def put(self, request):
    #     # 1. 获取用户和email并进行校验
    #     user = request.user
    #     serializer = self.get_serializer(user, data=request.data)
    #     print(serializer)
    #     serializer.is_valid(raise_exception=True)
    #     # get_serializer会根据类属性serializer_class指明的序列化器序列化data然后返回序列化对象,传入user指明这个序列化对象的id，这在定向修改信息的时候是必须的，有了这个才可以在下面save()函数的时候调用update()而不是create()
    #
    #     # 2. 设置用户的邮箱email
    #     # 3. 给用户的`email`发送验证邮件
    #     # 这两步封装在save()中执行，让后台在保存邮箱的同时发送验证信息
    #     serializer.save()
    #
    #     # 4. 返回应答
    #     serializer = self.get_serializer(user)
    #     return Response(serializer.data)
    def get_object(self):
        return self.request.user


# url(r'^user/$', views.UserDetailView.as_view())
class UserDetailView(RetrieveAPIView):
    """显示个人中心主页"""
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    # def get(self, request):
    #     # 1. 获取当前登录的用户user
    #     user = request.user
    #     # 2. 将用户数据进行序列化返回
    #     serializer = UserDetailSerializer(user)
    #     return Response(serializer.data)
    def get_object(self):
        """返回登录的用户"""
        return self.request.user


# POST /users/
# class UserView(CreateModelMixin, GenericAPIView):
class UserView(CreateAPIView):
    serializer_class = CreateUserSerializer

    # def post(self, request):
    #     """
    #     用户注册:
    #     1. 接收参数并进行参数校验(参数是否完整，密码是否一致，是否同意协议，短信验证码是否正确)
    #     2. 创建新用户
    #     3. 返回应答，注册成功
    #     """
    #     # 1. 接收参数并进行参数校验(参数是否完整，密码是否一致，是否同意协议，短信验证码是否正确)
    #     # serializer = CreateUserSerializer(data=request.data)
    #     # serializer = self.get_serializer(data=request.data)
    #     # serializer.is_valid(raise_exception=True)
    #
    #     # 2. 创建新用户
    #     # user = serializer.save()
    #
    #     # 3. 返回应答，注册成功
    #     # serializer = CreateUserSerializer(user)
    #     # serializer = self.get_serializer(user)
    #     # return Response(serializer.data, status=status.HTTP_201_CREATED)
    #
    #     return self.create(request)


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """用户名数量"""

    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """
    手机号数量
    """

    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)
